import time

from driver import get_driver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

import json


def get_companies_hrefs(country, place):
    all_card = []
    god = True
    place_href = []
    scroll_count = 0
    while god:
        try:
            driver = get_driver(url='https://yandex.ru/maps')
            if f'{country} {place}' == 'беларусь единоборства':
                break
            country_dict = {}
            time.sleep(1)
            driver.find_element(By.XPATH, '//button[@class="close-button _color_black _circle _offset_small"]'). \
                click()
            time.sleep(1)
            message = f'{country} {place}'
            driver.find_element(By.XPATH, "//input[@class='input__control _bold']").send_keys(f'{message}')
            ActionChains(driver).key_down(Keys.ENTER).perform()
            time.sleep(3)
            driver.find_element(By.XPATH, '//li[@class="search-snippet-view"]').click()
            time.sleep(1)
            while True:
                try:
                    all_cards = driver.find_elements(By.XPATH, '//li[@class="search-snippet-view"]')
                    end = driver.find_element(By.XPATH, '//div[@class="sidebar-view__expand-button-spacer"]')
                    ActionChains(driver).move_to_element(end).perform()
                    time.sleep(2)
                    all_card.append(all_cards)
                    scroll_count += 1
                    print(f'scroll number {scroll_count} running...')
                    crds = set(all_cards)
                    if scroll_count == 150:
                        all_card.clear()
                        all_cards.clear()
                        for card in crds:
                            href = card.find_element(By.TAG_NAME, 'div').find_element(By.TAG_NAME, 'div'). \
                                find_element(By.TAG_NAME, 'a').get_attribute('href')
                            place_href.append(href)
                            print(len(place_href))
                            print(href)

                        deleted_copy_href = set(place_href)
                        country_dict[country] = {place: f'{deleted_copy_href}'}
                        with open(f'{country}_{place}_hrefs.json', 'w', encoding='utf-8') as file:
                            json.dump(country_dict, fp=file, indent=4)
                            driver.close()
                            driver.quit()
                            god = False
                            break
                except Exception as ex:
                    print(f'RUNNING END {ex}')
                    break
        except Exception as ex:
            print(f'TRY SETUP DRIVER {ex}')
            continue
